import {userDeleteReq, userListReq, userSaveReq} from "@/service/user.ts";
import {SuccessCode} from "@/utils/request.ts";
import {Button, Form, message, Modal, Popconfirm, Space, Table, Typography} from "antd";
import {useForm} from "antd/es/form/Form";
import FormItem from "antd/es/form/FormItem";
import Input from "antd/es/input/Input";
import {ColumnsType} from "antd/es/table";
import {useEffect, useState} from "react";
import {useTranslation} from "react-i18next";
import styles from "./index.module.css"

const UserManage = () => {
    const [t,] = useTranslation()
    const [saveForm] = useForm()
    const [searchForm] = useForm()
    const [isShowCreateModal, setIsShowCreateModal] = useState(false)
    const [tableData, setTableData] = useState<API.UserListRespItem[]>([])
    const [tableLoading, setTableLoading] = useState(false)
    const tableColumns: ColumnsType<API.UserListRespItem> = [
        {
            title: "ID",
            dataIndex: "id",
            width: 200,
            render: value =>
                <Typography.Text style={{width: 100}}
                                 ellipsis={{tooltip: value}}>
                    {value}
                </Typography.Text>
        },
        {
            title: t('page.user.table.name'),
            dataIndex: "name"
        },
        {
            title: t('page.user.table.email'),
            dataIndex: "email"
        },
        {
            title: t('page.action'),
            width: 120,
            render: (_, record) => {
                return (
                    <Space>
                        <Popconfirm title={t('page.delete.prompt', {value: t("page.user")})}
                                    onConfirm={() => onDelete(record.id)}>
                            <Button type={"text"} danger>{t("page.delete")}</Button>
                        </Popconfirm>
                    </Space>
                )
            }
        }
    ]

    useEffect(() => {
        loadTableData()
    }, []);

    const loadTableData = () => {
        setTableLoading(true)
        userListReq({...searchForm.getFieldsValue()}).then(res => {
            if (res.code == SuccessCode) {
                setTableData(res.data.items)
            }
        }).finally(() => {
            setTableLoading(false)
        })
    }

    const onCreate = () => {
        userSaveReq({...saveForm.getFieldsValue()}).then(res => {
            if (res.code == SuccessCode) {
                message.success("创建成功")
                saveForm.resetFields()
                setIsShowCreateModal(false)
                loadTableData()
            } else {
                message.error(res.msg)
            }
        })
    }

    const onDelete = (id: string) => {
        userDeleteReq({id: id}).then(res => {
            if (res.code == SuccessCode) {
                message.success(t("page.operation.success"))
                loadTableData()
            } else {
                message.error(`${t("page.action.error")}: ${res.msg}`)
            }
        })
    }

    const renderCreateModal = () => {
        return (
            <Modal open={isShowCreateModal}
                   centered
                   title={t("page.user.createUser")}
                   onCancel={() => {
                       setIsShowCreateModal(false)
                       saveForm.resetFields()
                   }}
                   onOk={() => saveForm.submit()}
            >
                <Form form={saveForm} style={{padding: "20px 40px"}} onFinish={onCreate} autoComplete="off">
                    <FormItem label={t("page.user.table.name")} name={"username"}
                              rules={[{
                                  required: true,
                                  message: t("page.form.required.input", {value: t("page.user.table.name")})
                              }]}>
                        <Input placeholder={t("page.pleaseInput")} autoComplete="off"/>
                    </FormItem>
                    <FormItem label={t("page.user.table.password")} name={"password"}>
                        <Input type={"password"} placeholder={t("page.pleaseInput")} autoComplete={"new-password"}/>
                    </FormItem>
                </Form>
            </Modal>
        )
    }

    return (
        <div className={styles.UserManage}>
            <div className={"flex justify-between items-start"}>
                <Form form={searchForm} layout={'inline'} onKeyDown={(event) => {
                    if (event.key === "Enter") {
                        loadTableData()
                    }
                }}>
                    <FormItem label={t("page.user.table.name")} name={"username"}>
                        <Input placeholder={t("page.pleaseInput")}/>
                    </FormItem>
                    <FormItem>
                        <Button type={"primary"} onClick={loadTableData}>{t("page.search")}</Button>
                    </FormItem>
                    <FormItem>
                        <Button type={"dashed"} onClick={() => {
                            searchForm.resetFields()
                            loadTableData()
                        }}>{t("page.reset")}</Button>
                    </FormItem>
                </Form>
                <div className={styles.ActionWrap}>
                    <Space>
                        <Button type={"primary"} onClick={() => {
                            setIsShowCreateModal(true)
                        }}>{t("page.create")}</Button>
                    </Space>
                </div>
            </div>
            <Table style={{marginTop: 20}} loading={tableLoading} columns={tableColumns} dataSource={tableData}
                   rowKey={"id"}/>
            {renderCreateModal()}
        </div>
    );
};

export default UserManage;
